import { baseConfig } from '@/config'
import { useAuth, usePermission } from '@/hooks'
import {  logindata,  } from '@/api'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'
import { getStorage, setStorage, removeStorage } from '@/utils'

NProgress.configure({ showSpinner: false })

const { hasLogin } = useAuth()
const { state: userPermissionState, getPermissions, hasPermission } = usePermission()

export const beforeEachGuard = async (to) => {
	NProgress.start()
	
		const res = await logindata()
		setStorage('bgc', res.data)
	var data = window.location.search.split('=')
	// data = ['?token', '1f391c6c-51d9-11ed-8dd2-00163e2292ca']
	if (data[0] == '?token') {
		const { setToken } = useAuth()
		setToken(data[1])
		const redirect = window.location.href
		console.log(redirect)
		window.location.href = redirect.replace(/[?&]token=[^&]*&?/g, '')

	} else {
		console.log(localStorage.token)
		if (localStorage.token == undefined) {
			window.open(window.location.origin + '/app/base/', '_self')
		}
	}

	// 登录状态
	if (!hasLogin.value) {
		if (!to.path.includes('/auth')) {
			return { name: 'login', query: { redirect: to.fullPath } }
		}
	}
	// 权限
	if (!userPermissionState.fetched) {
		await getPermissions()
	}
	if (!hasPermission(to.meta.permissions)) {
		return { name: '404' }
	}
	// console.log('跳转')
}

export const afterEachGuard = (to) => {
	NProgress.done()
	document.title = `${to.meta?.title ? to.meta.title + ' - ' : ''}${baseConfig.title}`
}
